<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\AdminCheckEnum;
use App\Enums\CheckStatusEnum;
use App\Events\CheckSuccess;
use App\Exceptions\ApiException;
use App\Format\CheckSuccessFormat;
use App\Format\RentHouseFormat;
use App\Models\RentHouse;
use App\Models\UserProfile;
use Illuminate\Support\Facades\Log;

class RentHouseService
{
    public function setRentHouseForCheck(RentHouseFormat $rentHouseFormat, int $userId)
    {
        $rentHouseFormat->setCheckStatus(CheckStatusEnum::CHECK_ING);
        $rentHouseFormat->setPushTime(time());
        $id = $rentHouseFormat->getId();
        $rentHouseFormat->setId(null);
        $pushUserId = $rentHouseFormat->getUserId();
        /** @var null|UserProfile $userProfile */
        $userProfile = UserProfile::query()->where('user_id', $pushUserId)->select('check_status')->first();
        if (empty($userProfile)) {
            throw new ApiException('用户不存在', 1);
        }
        if ($userProfile->check_status != CheckStatusEnum::CHECK_ADOPT) {
            throw new ApiException('个人信息审核通过的用户才能发布招聘', 1);
        }
        if (empty($id)) {
            $count = RentHouse::query()->count();
            $rentHouseFormat->setOrderNum($count + 1);
            RentHouse::query()->create($rentHouseFormat->toArrayNotNull());
            return true;
        }
        /** @var null|RentHouse $rentHouse */
        $rentHouse = RentHouse::query()->find($id);
        if (empty($rentHouse)) {
            throw new ApiException('数据不存在', 1);
        }
        if ($rentHouse->user_id != $userId) {
            Log::error('修改非自己的租房', [
                'user_id' => $userId,
                'data_user_id' => $rentHouse->user_id,
            ]);
            throw new ApiException('非法操作', 1);
        }
        $rentHouse->update($rentHouseFormat->toArrayNotNull());
        return true;
    }

    public function checkRentHouse(int $id, int $checkStatus, ?string $checkMessage)
    {
        /** @var null|RentHouse $rentHouse */
        $rentHouse = RentHouse::query()->find($id);
        if (empty($rentHouse)) {
            throw new ApiException('数据不存在', 1);
        }
        $rentHouse->check_status = $checkStatus;
        if ($checkMessage) {
            $rentHouse->check_message = $checkMessage;
        }
        $rentHouse->push_time = time();
        $rentHouse->expire_time = time() + (3600 * 24 * 30);
        // 默认一个月过期
        $rentHouse->save();
        event(new CheckSuccess(new CheckSuccessFormat([
            'check_status' => $checkStatus,
            'check_type' => AdminCheckEnum::CHECK_HOUSE_RENT,
            'user_id' => $rentHouse->user_id,
        ])));
        return true;
    }

    public function setExpireTime(int $id, int $expireTime)
    {
        /** @var null|RentHouse $rentHouse */
        $rentHouse = RentHouse::query()->find($id);
        if (empty($rentHouse)) {
            throw new ApiException('数据不存在', 1);
        }
        if ($rentHouse->check_status != CheckStatusEnum::CHECK_ADOPT) {
            throw new ApiException('不能为未审核通过的租房设置过期时间', 1);
        }
        $rentHouse->expire_time = $expireTime;
        $rentHouse->save();
        return true;
    }

    public function getRentHouseList(int $page, int $pageSize, array $search)
    {
        $builder = RentHouse::query()
            ->where('expire_time', '>', time())
            ->where('check_status', CheckStatusEnum::CHECK_ADOPT);

        if (isset($search['start_date'], $search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['start_date']) && ! isset($search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
        }
        if (! isset($search['start_date']) && isset($search['end_date'])) {
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['address'])) {
            $builder->where('address', 'like', '%' . $search['address'] . '%');
        }
        $count = $builder->count();
        $list = $builder
            ->orderBy('order_num')
            ->orderByDesc('push_time')
            ->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function getRentHouseAdminList(int $page, int $pageSize, array $search)
    {
        $builder = RentHouse::query();

        if (isset($search['start_date'], $search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['start_date']) && ! isset($search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
        }
        if (! isset($search['start_date']) && isset($search['end_date'])) {
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['address'])) {
            $builder->where('address', 'like', '%' . $search['address'] . '%');
        }
        if (isset($search['check_status'])) {
            $builder->where('check_status', $search['check_status']);
        }
        $count = $builder->count();
        $list = $builder
            ->orderBy('order_num')
            ->orderByDesc('push_time')
            ->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function detail(int $id)
    {
        $rentHouse = RentHouse::query()
            ->where('check_status', CheckStatusEnum::CHECK_ADOPT)
            ->where('expire_time', '>', time())
            ->find($id);
        if (empty($rentHouse)) {
            throw new ApiException('数据不存在', 1);
        }
        return $rentHouse;
    }

    public function detailAdmin(int $id)
    {
        /** @var null|RentHouse $rentHouse */
        $rentHouse = RentHouse::query()->find($id);
        if (empty($rentHouse)) {
            throw new ApiException('数据不存在', 1);
        }
        return $rentHouse;
    }

    public function delete(int $id)
    {
        /** @var null|RentHouse $rentHouse */
        $rentHouse = RentHouse::query()->find($id);
        if (empty($rentHouse)) {
            throw new ApiException('数据不存在', 1);
        }
        $rentHouse->delete();
        return true;
    }

    public function getMyRentedHouse(int $userId, int $page, int $pageSize)
    {
        $builder = RentHouse::query()->where('user_id', $userId);

        $count = $builder->count();

        $list = $builder->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function getMyRentedHouseDetail(int $id, int $userId)
    {
        $rentHouse = RentHouse::query()->where('user_id', $userId)->find($id);
        if (empty($rentHouse)) {
            throw new ApiException('数据不存在', 1);
        }
        return $rentHouse;
    }

    public function setOrder(int $id, int $orderNum)
    {
        /** @var null|RentHouse $rentHouse */
        $rentHouse = RentHouse::query()->find($id);
        if (empty($rentHouse)) {
            throw new ApiException('数据不存在', 1);
        }
        $rentHouse->order_num = $orderNum;
        $rentHouse->save();
        return true;
    }
}
